const chalk = require('chalk');

const express = require('express');
const fs = require('fs');
const path = require('path');
const history = require('connect-history-api-fallback');


// 标记是服务端启动
process.env.IS_SERVER = true;

[`.env.${process.env.NODE_ENV || 'production'}`, `.env.${process.env.NODE_ENV || 'production'}.local`].forEach((dotenvFilePath) => {
  if (fs.existsSync(dotenvFilePath)) {
    require('dotenv').config({
      path: dotenvFilePath,
      override: true,
    });
  }
});

const app = express();

const port = process.env.HTTP_PORT || 7001;


// 设置跨域访问
app.all('*', (req, res, next) => {
  // 设置允许跨域的域名，*代表允许任意域名跨域
  res.header('Access-Control-Allow-Origin',  '*');
  // 允许的header类型
  res.header('Access-Control-Allow-Headers', '*');
  // 跨域允许的请求方式
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  // 可以带cookies
  res.header('Access-Control-Allow-Credentials', true);
  if (req.method === 'OPTIONS') {
    res.sendStatus(204);
  } else {
    next();
  }
});
// 拦截接口请求，修改请求类型
app.use(`${process.env.VUE_APP_BASE_API}/*`, (req, res, next) => {
  req.headers.accept = 'application/json, text/plain, */*';
  next();
});

app.use(
  '/static',
  express.static(path.join(__dirname, '../dist/static')),
);

app.use(history({
  verbose: true,
  rewrites: [
    { from: /^\/m/, to: '/m/index.html' },
    { from: /./, to: '/index.html' },
  ],
}));

app.use('/health', (req, res) => {
  res.send('ok');
});


const init = require('./init');

init(app);

app.use(
  '/',
  express.static(path.join(__dirname, '../dist'), {
    index: ['index.html', '/'],
  }),
);


app.listen(port, () => {
  console.log(chalk.green(`> 服务已启动  http://localhost:${port}`));
});
